<%--
  Created by IntelliJ IDEA.
  User: lqq
  Date: 2017/6/28
  Time: 12:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<html>
<head>

    <base href="<%=basePath%>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <script src="jquery/jquery-3.2.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css">
    <title>员工信息</title>
</head>
<script>
    var totalPages, curPage;
    $(function () {
        on_curPage(1);
    });

    function on_curPage(curPage) {
        $.post("indexWithJson",
            {curPage: curPage},
            function (data) {
                bulid_emp(data);
                bulid_page_desc(data);
                bulid_page_info(data);
            }
        );
    }

    function bulid_emp(data) {
        $("#emp_table tbody").empty();
        var emp = data.extend.pageInfo.list;
        $.each(emp, function (index, item) {

            var checkItem = $("<td><input type='checkbox' class='check_item'/></td>");
            var empId = $("<td></td>").append(item.id);
            var empName = $("<td></td>").append(item.name);
            var empSex = $("<td></td>").append(item.sex);
            var empAge = $("<td></td>").append(item.age);
            var empDept = $("<td></td>").append(item.dept.name);
            var btnEdit = $("<td></td>").append(
                $("<button></button>").addClass("btn btn-primary btn-sm btn_edit").append(
                    $("<span></span>").addClass("glyphicon glyphicon-pencil")
                ).append("修改").attr("employee_id", item.id)
            ).append(" ").append(
                $("<button></button>").addClass("btn btn-danger btn-sm btn_delete").append(
                    $("<span></span>").addClass("glyphicon glyphicon-trash")
                ).append("删除").attr("employee_id", item.id)
            );


            var tr_table = $("<tr></tr>").append(checkItem).append(empId).append(empName).append(empSex)
                .append(empAge).append(empDept).append(btnEdit).appendTo("#emp_table tbody");

        });
    }
    function bulid_page_desc(data) {
        $("#page_desc").empty();
        var pageInfo = data.extend.pageInfo;
        $("#page_desc").append("当前页:" + pageInfo.pageNum + "&nbsp;&nbsp;&nbsp;&nbsp;共" + pageInfo.pageNum + "/" + pageInfo.pages + "页");
        totalPages = pageInfo.pages;
        curPage = pageInfo.pageNum;

    }
    function bulid_page_info(data) {
        $("#page_info").empty();
        var pageInfo = data.extend.pageInfo;

        var firstPage = $("<li></li>").append(
            $("<a href='javaScript:'></a>").append("首页")
        );
        firstPage.click(function () {
            on_curPage(1);
        });
        var prePage = $("<li></li>").append(
            $("<a href='javaScript:'></a>").append(
                $("<span></span>").append("&laquo;")
            )
        );
        prePage.click(function () {
            on_curPage(pageInfo.pageNum - 1);
        });
        if (pageInfo.hasPreviousPage == false) {
            firstPage.addClass("disabled");
            prePage.addClass("disabled");
        }
        $("#page_info").append(firstPage).append(prePage);
        $.each(pageInfo.navigatepageNums, function (index, item) {
            var page = $("<li></li>").append(
                $("<a href='javaScript:'></a>").append(item)
            );
            if (pageInfo.pageNum == item) {
                page.addClass("active");
            }
            $("#page_info").append(page);
            page.click(function () {
                on_curPage(item);
            });
        });
        var nextPage = $("<li></li>").append(
            $("<a href='javaScript:'></a>").append(
                $("<span></span>").append("&raquo;")
            )
        );
        nextPage.click(function () {
            on_curPage(pageInfo.pageNum + 1);
        });
        var lastPage = $("<li></li>").append(
            $("<a href='javaScript:'></a>").append("尾页")
        );
        lastPage.click(function () {
            on_curPage(pageInfo.pages);
        });
        if (pageInfo.hasNextPage == false) {
            nextPage.addClass("disabled");
            lastPage.addClass("disabled");
        }
        $("#page_info").append(nextPage).append(lastPage);

    }

</script>
<body>

<div class="container">

    <!-- 员工修改-->
    <div class="modal fade" id="emp_edit_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">修改员工信息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="txt_edit_name" class="col-sm-2 control-label">姓名：</label>
                            <div class="col-sm-10">
                                <input type="email" class="form-control" id="txt_edit_name" placeholder="请输入员工姓名..."
                                       name="name" disabled="disabled">
                                <span class="help-block"></span>
                                <span class="" aria-hidden="true"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10" id="txt_edit_sex">
                                <label for="txt_edit_sex1" class="radio-inline">
                                    <input type="radio" name="sex" id="txt_edit_sex1" value="男"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="sex" id="txt_edit_sex2" value="女"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="txt_edit_age" class="col-sm-2 control-label">年龄</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="txt_edit_age" placeholder="请输入年龄...."
                                       name="age">
                                <span class="help-block"></span>
                                <span class="" aria-hidden="true"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="txt_edit_dept" class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-4" id="txt_edit_dept">
                                <select class="form-control" id="dept_edit_info" name="deptId">

                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="btn_edit_save">更新</button>
                </div>

            </div>
        </div>
    </div>

    <!-- 员工添加-->
    <div class="modal fade" id="emp_add_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">添加员工</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="txt_name" class="col-sm-2 control-label">姓名：</label>
                            <div class="col-sm-10">
                                <input type="email" class="form-control" id="txt_name" placeholder="请输入员工姓名..."
                                       name="name">
                                <span class="help-block"></span>
                                <span class="" aria-hidden="true"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label for="txt_sex1" class="radio-inline">
                                    <input type="radio" name="sex" id="txt_sex1" value="男" checked="checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="sex" id="txt_sex2" value="女"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="txt_age" class="col-sm-2 control-label">年龄</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="txt_age" placeholder="请输入年龄...." name="age">
                                <span class="help-block"></span>
                                <span class="" aria-hidden="true"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="txt_dept" class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-4" id="txt_dept">
                                <select class="form-control" id="dept_info" name="deptId">

                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="btn_save">保存</button>
                </div>

            </div>
        </div>
    </div>


    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSH-CRUP</h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary" id="btn_add_emp">新增</button>
            <button class="btn btn-danger" id="btn_delete_emp_batch">删除</button>
        </div>
    </div>
    <%--表格--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped table-hover" id="emp_table">
                <thead>
                <tr>
                    <th><input type="checkbox" id="txt_checkbox"></th>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>部门</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <%--分页信息--%>
    <div class="row">
        <div class="col-md-6" id="page_desc">

        </div>
        <div class="col-md-6">
            <nav aria-label="Page navigation">
                <ul class="pagination" id="page_info">

                </ul>
            </nav>
        </div>
    </div>
</div>
</body>
<script>
    function reset_form(ele) {
        $(ele)[0].reset();
        $("#txt_name").parent().removeClass("has-success has-error has-feedback");
        $("#txt_name").next("span").removeAttr("error_employee");
        $("#txt_age").parent().removeClass("has-success has-error has-feedback");
        $(ele).find("span").removeClass("glyphicon glyphicon-remove form-control-feedback").text("");
    }
    $(function () {

        //全部选择
        $("#txt_checkbox").click(function () {
            if ($(this).prop("checked")) {
                $(".check_item").prop("checked", true);
            } else {
                $(".check_item").prop("checked", false);
            }
        });

        //批量删除员工
        $("#btn_delete_emp_batch").click(function () {
            var empNames = "";
            var empIds = "";
            $.each($(".check_item:checked").parents("tr").find("td:eq(2)"), function () {
                empNames += $(this).text() + ",";
            });
            empNames = empNames.substring(0,empNames.length - 1);

            $.each($(".check_item:checked").parents("tr").find("td:eq(1)"),function(){
                empIds += $(this).text() + "-";
            });
            empIds = empIds.substring(0,empIds.length-1);
            if($.trim(empNames) == ""){
                alert("请先选择员工!");
                return false;
            }
            if(confirm("确定要删除【"+empNames+"】吗?")){
                $.ajax({
                   url:"emp/"+empIds,
                    type:"POST",
                    data:"_method=DELETE",
                    success:function(result){
                       alert(result.message);
                       on_curPage(curPage);
                    }
                });
            }


        });

        //单一选择监听
        $(document).on("click", ".check_item", function () {
            if ($(".check_item:checked").length == $(".check_item").length) {
                $("#txt_checkbox").prop("checked", true);
            } else {
                $("#txt_checkbox").prop("checked", false);
            }
        });

        //删除员工
        $(document).on("click", ".btn_delete", function () {
            if (confirm("确定要删除员工【" + $(this).parents("tr").find("td:eq(2)").text() + "】吗？")) {
                $.ajax({
                    url: "emp/" + $(this).attr("employee_id"),
                    type: "POST",
                    data: "_method=DELETE",
                    success: function (result) {
                        on_curPage(curPage);
                    }
                });
            }
        });


        //添加员工事件
        $("#btn_add_emp").click(function () {
            reset_form($("#emp_add_modal form"));
            getAllDept($("#dept_info"));
            $("#emp_add_modal").modal({
                backdrop: "static"
            });
        });

        //修改员工事件
        $(document).on("click", ".btn_edit", function () {

            reset_form($("#emp_edit_modal form"));
            getAllDept($("#dept_edit_info"));
            getEmployee($(this).attr("employee_id"));
            $("#btn_edit_save").attr("employee_id", $(this).attr("employee_id"));
            $("#emp_edit_modal").modal({
                backdrop: "static"
            });
        });
        //保存修改员工信息事件
        $("#btn_edit_save").click(function () {
            var form_data = $("#emp_edit_modal form").serialize();
            if (!validateEditForm()) {
                return false;
            }

            $.ajax(
                {
                    url: "emp/" + $(this).attr("employee_id"),
                    type: "POST",
                    data: form_data + "&_method=PUT",
                    success: function (result) {
                        if (undefined != result.extend.fieldErrors) {


                            if (undefined != result.extend.fieldErrors.age) {
                                show_validate_message($("#txt_edit_age"), "error", result.extend.fieldErrors.age);
                                return false;
                            }
                        }


                        $("#emp_edit_modal").modal("hide");
                        on_curPage(curPage);
                    }
                }
            );
        });

        //根据员工id获取员工信息
        function getEmployee(id) {
            $.ajax({
                url: "emp/" + id,
                type: "GET",
                success: function (result) {
                    $("#txt_edit_name").val(result.extend.employee.name);
                    $("#txt_edit_age").val(result.extend.employee.age);
                    $("#txt_edit_sex input").val([result.extend.employee.sex]);
                    $("#emp_edit_modal form select").val(result.extend.employee.deptId);
                }
            })
        }

        //校验添加表单
        function validateForm() {
            var name = $("#txt_name").val();
            var age = $("#txt_age").val();
            var nameRegex = /^([a-z0-9_-]{6,16})|([\u2E80-\u9FFF]+)$/;
            var ageRegex = /^[1-9]{1}[0-9]{1}$/;
            if (!nameRegex.test(name)) {
                show_validate_message($("#txt_name"), "error", "用户名由5~16位字母和数字组成或中文组成!");
                return false;
            } else {
                show_validate_message($("#txt_name"), "success", "");
            }
            if (!ageRegex.test(age)) {
                show_validate_message($("#txt_age"), "error", "年龄不合法!");

                return false;
            } else {
                show_validate_message($("#txt_age"), "success", "");
            }
            return true;
        }

        //校验修改表单
        function validateEditForm() {

            var age = $("#txt_edit_age").val();

            var ageRegex = /^[1-9]{1}[0-9]{1}$/;

            if (!ageRegex.test(age)) {
                show_validate_message($("#txt_edit_age"), "error", "年龄不合法!");

                return false;
            } else {
                show_validate_message($("#txt_edit_age"), "success", "");
            }
            return true;
        }

        //校验表单数据
        function show_validate_message(ob, status, message) {
            if (ob.next("span").attr("error_employee") == "yes") {
                return;
            }
            ob.parent().removeClass("has-error has-success has-feedback");
            ob.next("span").text("");
            ob.next().next().removeClass("glyphicon glyphicon-remove form-control-feedback");

            if (status == "success") {
                ob.parent().addClass("has-success");
                ob.next("span").text(message);

            } else {
                ob.parent().addClass("has-error has-feedback");
                ob.next("span").text(message);
                ob.next().next().addClass("glyphicon glyphicon-remove form-control-feedback");
            }
        }


        //员工名监听事件
        $("#txt_name").change(function () {
            $("#txt_name").next("span").removeAttr("error_employee");
            $.ajax({
                url: "emp/checkUser",
                type: "post",
                data: "empName=" + this.value,
                success: function (result) {
                    if (result.code == 100) {
                        show_validate_message($("#txt_name"), "success", "用户名可用");
                        $("#btn_save").attr("ajax_va", "success");
                    } else {
                        show_validate_message($("#txt_name"), "error", result.extend.error_name);
                        $("#txt_name").next("span").attr("error_employee", "yes");
                        $("#btn_save").attr("ajax_va", "error");
                    }
                }
            });
        });

        //保存添加的员工事件
        $("#btn_save").click(function () {
            var form_data = $("#emp_add_modal form").serialize();
            if (!validateForm()) {
                return false;
            }
            if ($("#btn_save").attr("ajax_va") == "error") {
                return false;
            }
            $.ajax(
                {
                    url: "emp",
                    type: "POST",
                    data: form_data,
                    success: function (result) {
                        if (undefined != result.extend.fieldErrors) {

                            if (undefined != result.extend.fieldErrors.name) {
                                show_validate_message($("#txt_name"), "error", result.extend.fieldErrors.name);
                                return false;
                            }
                            if (undefined != result.extend.fieldErrors.age) {
                                show_validate_message($("#txt_age"), "error", result.extend.fieldErrors.age);
                                return false;
                            }
                        }


                        $("#emp_add_modal").modal("hide");
                        on_curPage(totalPages);
                    }
                }
            );
        });
    })
    function getAllDept(ele) {
        $.get("dept/getAll",
            function (data) {
                ele.empty();
                $.each(data.extend.dept_list, function () {
                    $("<option></option>").attr("value", this.id).append(this.name).appendTo(ele);
                });
            }
        );
    }
</script>
</html>
